<template>
  <div>
    <van-nav-bar title="HOME" />
    <!-- 成功获取数据 -->
    <div class="success">
    <van-notice-bar v-if="city" scrollable :text="weatherText" />
        <!-- 图片 -->
        <van-image
          v-if="info.picUrl"
          width="10rem"
          height="5.625rem"
          fit="contain"
          :src="info.picUrl"
        />
        <!-- 文字 -->
        <p class="text">{{text}}</p>
        <p v-if="info.mp3url" class="song"><audio autoplay loop controls :src="info.mp3url"></audio></p>
        <p v-if="info.mp3url" class="songText">{{ songText }}</p>
        <p v-if="info.mp3url" class="songBtn">
          <van-button @click="changeSong" color="linear-gradient(to right, #ff6034, #ee0a24)">
            换 一 首
          </van-button>
        </p>
    </div>
    <!-- 获取数据失败 -->
    <div class="error"></div>
  </div>
</template>

<script>
import { randomSentence, weather, song } from '@/api'

export default {
  name: 'home',
  data () {
    return {
      text: '',
      city: '',
      weatherData: {},
      info: {}
    }
  },

  computed: {
    weatherText () {
      return `您当前所在城市${this.city}, 今日天气${this.weatherData.type}, 最${this.weatherData.low}, 最${this.weatherData.high}, 温馨提示: ${this.weatherData.tip}`
    },
    songText () {
      return `歌名：${this.info.name}   作者：${this.info.auther}`
    }
  },

  created () {
    this.getData()
  },

  methods: {
    // 获取所有的数据
    async getData () {
      this.getText()
      this.getWeather()
      this.getSong()
    },

    // 获取文字
    async getText () {
      try {
        const { data: res } = await randomSentence()
        this.text = res.ishan
      } catch (err) {
        this.getText()
      }
    },
    // 获取文字
    async getWeather () {
      try {
        const { data: res } = await weather()
        this.city = res.city
        this.weatherData = res.info
      } catch (err) {
        this.$toast('获取天气失败')
      }
    },
    // 获取歌曲
    async getSong () {
      try {
        const { data: res } = await song()
        console.log(res)
        this.info = res.info
      } catch (err) {
        this.$toast('获取歌曲失败')
      }
    },
    // 更换歌曲
    changeSong () {
      this.getText()
      this.getSong()
    }
  }
}
</script>

<style scoped lang='less'>
.text {
  padding: 0 20px;
  font-size: 32px;
  text-align: center;
}
.van-notice-bar {
  margin-bottom: 50px;
}
.song {
  width: 100%;
  height: 100px;
  audio {
    width: 100%;
    height: 100%;
  }
}
.songText {
  font-size: 28px;
  text-align: center;
}
.songBtn {
  text-align: center;
}
.van-button {
  width: 400px;
  border-radius: 40px;
}
</style>
